<template>
  <div class="voucher-manage">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>{{ texts.title }}</h1>
      <div class="header-actions">
        <el-button type="primary" @click="openVoucherDialog()">
          <el-icon><Plus /></el-icon>
          {{ texts.add }}
        </el-button>
        <el-button @click="exportVouchers">
          <el-icon><Download /></el-icon>
          {{ texts.export }}
        </el-button>
      </div>
    </div>

    <!-- 搜索过滤器 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item :label="texts.voucherNo">
          <el-input 
            v-model="searchForm.voucherNo" 
            :placeholder="texts.voucherNoPlaceholder"
            clearable
            style="width: 180px;"
          />
        </el-form-item>
        <el-form-item :label="texts.voucherType">
          <el-select 
            v-model="searchForm.voucherType" 
            :placeholder="texts.pleaseSelect" 
            clearable
            style="width: 140px;"
          >
            <el-option :label="texts.purchaseVoucher" value="purchase" />
            <el-option :label="texts.salesVoucher" value="sales" />
          </el-select>
        </el-form-item>
        <el-form-item :label="texts.dateRange">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            :range-separator="texts.to"
            :start-placeholder="texts.startDate"
            :end-placeholder="texts.endDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 280px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchVouchers">
            <el-icon><Search /></el-icon>
            {{ texts.search }}
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            {{ texts.reset }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 凭证列表 -->
    <el-card class="table-card">
      <!-- Tab页切换 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="voucher-tabs">
        <el-tab-pane label="待审批" name="pending">
          <template #label>
            <span class="tab-label">
              <el-icon><Clock /></el-icon>
              待审批
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="已审批" name="approved">
          <template #label>
            <span class="tab-label">
              <el-icon><CircleCheck /></el-icon>
              已审批
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>

      <el-table :data="filteredVouchersByTab" stripe border v-loading="loading">
        <el-table-column prop="voucherNo" :label="texts.voucherNo" width="150" />
        <el-table-column prop="voucherType" :label="texts.voucherType" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.voucherType === 'purchase' ? 'warning' : 'success'">
              {{ scope.row.voucherType === 'purchase' ? texts.purchase : texts.sales }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderId" :label="texts.orderId" width="120" />
        <el-table-column prop="customerName" :label="texts.customerName" width="150" />
        <el-table-column prop="totalAmount" :label="texts.totalAmount" width="120" align="right">
          <template #default="scope">
            ¥{{ scope.row.totalAmount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="voucherDate" :label="texts.voucherDate" width="120" />
        <el-table-column prop="status" :label="texts.status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="texts.actions" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewVoucher(scope.row)">
              <el-icon><View /></el-icon>
              {{ texts.view }}
            </el-button>
            <el-button size="small" type="primary" @click="editVoucher(scope.row)" v-if="scope.row.status === 'pending'">
              <el-icon><Edit /></el-icon>
              {{ texts.edit }}
            </el-button>
            <el-button size="small" type="success" @click="approveVoucher(scope.row)" v-if="scope.row.status === 'pending'">
              <el-icon><CircleCheck /></el-icon>
              {{ texts.approve }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteVoucher(scope.row)" v-if="scope.row.status === 'pending'">
              <el-icon><Delete /></el-icon>
              {{ texts.delete }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 凭证详情/编辑页面 -->
    <div v-if="voucherDialog.visible" class="voucher-form-page">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-page-header @back="closeVoucherDialog" :title="voucherDialog.isEdit ? '编辑凭证' : '新增凭证'">
          <template #content>
            <span class="page-title">{{ voucherDialog.isEdit ? '编辑凭证' : '新增凭证' }}</span>
          </template>
        </el-page-header>
      </div>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <el-card class="form-card">
          <el-form :model="voucherDialog.form" :rules="voucherRules" ref="voucherFormRef" label-width="120px">
            <!-- 基本信息 -->
            <div class="form-section">
              <h3 class="section-title">{{ texts.basicInfo }}</h3>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="texts.voucherNo" prop="voucherNo">
                    <el-input v-model="voucherDialog.form.voucherNo" :placeholder="texts.autoGenerated" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="'凭证类型'" prop="voucherType">
                    <el-select v-model="voucherDialog.form.voucherType" :placeholder="'请选择'">
                      <el-option label="采购凭证" value="purchase" />
                      <el-option label="销售凭证" value="sales" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="订单号" prop="orderId">
                    <div class="order-selector">
                      <el-input 
                        v-model="voucherDialog.form.orderId" 
                        placeholder="请输入订单号"
                        readonly
                        @click="showOrderSelector = true"
                      >
                        <template #append>
                          <el-button @click="showOrderSelector = true">
                            <el-icon><Search /></el-icon>
                          </el-button>
                        </template>
                      </el-input>
                      <div v-if="voucherDialog.form.orderId" class="order-info">
                        <el-tag size="small" type="info">{{ getOrderInfo(voucherDialog.form.orderId)?.orderType || '未知订单' }}</el-tag>
                        <span class="order-amount">¥{{ getOrderInfo(voucherDialog.form.orderId)?.amount?.toLocaleString() || '0' }}</span>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户名称" prop="customerName">
                    <el-input v-model="voucherDialog.form.customerName" placeholder="请输入客户名称" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="凭证日期" prop="voucherDate">
                    <el-date-picker
                      v-model="voucherDialog.form.voucherDate"
                      type="date"
                      :placeholder="'请选择'"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="总金额" prop="totalAmount">
                    <el-input-number 
                      v-model="voucherDialog.form.totalAmount" 
                      :min="0" 
                      :precision="2" 
                      style="width: 100%"
                      placeholder="请输入总金额"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item :label="'摘要'" prop="summary">
                <el-input 
                  v-model="voucherDialog.form.summary" 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入摘要"
                />
              </el-form-item>
            </div>

            <!-- 会计分录预览 -->
            <div class="form-section" v-if="voucherDialog.form.orderId">
                              <h3 class="section-title">会计分录预览</h3>
              <div class="accounting-entries-preview">
                <div class="preview-header">
                  <el-alert
                    title="会计分录将根据订单类型和金额自动生成"
                    type="info"
                    :closable="false"
                    show-icon
                  />
                </div>
                <el-table :data="previewEntries" border stripe size="small">
                  <el-table-column prop="accountCode" label="科目代码" width="100" />
                  <el-table-column prop="accountName" label="科目名称" min-width="120" />
                  <el-table-column label="借方金额" width="100" align="right">
                    <template #default="scope">
                      <span v-if="scope.row.debitAmount > 0" class="debit-amount">
                        ¥{{ scope.row.debitAmount.toLocaleString() }}
                      </span>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="贷方金额" width="100" align="right">
                    <template #default="scope">
                      <span v-if="scope.row.creditAmount > 0" class="credit-amount">
                        ¥{{ scope.row.creditAmount.toLocaleString() }}
                      </span>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="summary" :label="'摘要'" min-width="150" />
                  <el-table-column prop="auxiliary" label="辅助" width="100" />
                  <el-table-column prop="auxiliaryValue" label="辅助值" width="120" />
                </el-table>
                <div class="preview-footer">
                                      <el-tag type="success" size="small">借贷平衡检查：¥{{ voucherDialog.form.totalAmount?.toLocaleString() }}</el-tag>
                </div>
              </div>
            </div>
          </el-form>
        </el-card>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button @click="closeVoucherDialog">{{ texts.cancel }}</el-button>
          <el-button type="primary" @click="saveVoucher">{{ texts.save }}</el-button>
        </div>
      </div>
    </div>

    <!-- 凭证详情弹窗 -->
    <el-dialog 
      v-model="voucherDetailDialog.visible" 
      title="凭证详情"
      width="80%"
      @close="closeVoucherDetailDialog"
    >
      <div v-if="voucherDetailDialog.data" class="voucher-detail">
        <!-- 凭证基本信息 -->
        <el-card class="detail-section">
          <template #header>
            <div class="section-header">
              <span class="section-title">凭证基本信息</span>
              <el-tag :type="getStatusType(voucherDetailDialog.data.status)" size="small">
                {{ getStatusText(voucherDetailDialog.data.status) }}
              </el-tag>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <span class="label">凭证编号：</span>
                <span class="value">{{ voucherDetailDialog.data.voucherNo }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="label">凭证类型：</span>
                <el-tag :type="voucherDetailDialog.data.voucherType === 'sales' ? 'success' : 'warning'">
                  {{ voucherDetailDialog.data.voucherType === 'sales' ? '销售凭证' : '采购凭证' }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="label">凭证日期：</span>
                <span class="value">{{ voucherDetailDialog.data.voucherDate }}</span>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <span class="label">关联订单：</span>
                <span class="value">{{ voucherDetailDialog.data.orderId || '无' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="label">客户名称：</span>
                <span class="value">{{ voucherDetailDialog.data.customerName }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="label">总金额：</span>
                <span class="value amount">¥{{ voucherDetailDialog.data.totalAmount?.toLocaleString() }}</span>
              </div>
            </el-col>
          </el-row>
          
          <div class="detail-item">
            <span class="label">摘要：</span>
            <span class="value">{{ voucherDetailDialog.data.summary }}</span>
          </div>
        </el-card>

        <!-- 会计分录 -->
        <el-card class="detail-section">
          <template #header>
                          <span class="section-title">会计分录</span>
          </template>
          
          <el-table :data="voucherDetailDialog.data.entries || []" border stripe>
            <el-table-column prop="accountCode" label="科目代码" width="120" />
            <el-table-column prop="accountName" label="科目名称" min-width="150" />
            <el-table-column label="借方金额" width="120" align="right">
              <template #default="scope">
                <span v-if="scope.row.debitAmount > 0" class="debit-amount">
                  ¥{{ scope.row.debitAmount.toLocaleString() }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="贷方金额" width="120" align="right">
              <template #default="scope">
                <span v-if="scope.row.creditAmount > 0" class="credit-amount">
                  ¥{{ scope.row.creditAmount.toLocaleString() }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="summary" :label="'摘要'" min-width="200" />
            <el-table-column prop="auxiliary" label="辅助" width="120" />
            <el-table-column prop="auxiliaryValue" label="辅助值" width="120" />
          </el-table>
        </el-card>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeVoucherDetailDialog">关闭</el-button>
          <el-button type="primary" @click="editVoucherFromDetail" v-if="voucherDetailDialog.data?.status === 'pending'">
            编辑凭证
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单选择器弹窗 -->
    <el-dialog 
      v-model="showOrderSelector" 
      title="选择关联订单"
      width="80%"
      @close="closeOrderSelector"
    >
      <div class="order-selector-content">
        <!-- 订单搜索 -->
        <el-form :model="orderSearchForm" inline class="order-search-form">
          <el-form-item label="订单号">
            <el-input v-model="orderSearchForm.orderNo" placeholder="请输入订单号" clearable />
          </el-form-item>
          <el-form-item label="订单类型">
            <el-select v-model="orderSearchForm.orderType" placeholder="请选择订单类型" clearable>
              <el-option label="销售订单" value="sales" />
              <el-option label="采购订单" value="purchase" />
              <el-option label="退款订单" value="refund" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="orderSearchForm.orderStatus" placeholder="请选择订单状态" clearable>
              <el-option label="已完成" value="completed" />
              <el-option label="处理中" value="processing" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchOrders">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetOrderSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 订单列表 -->
        <el-table 
          :data="filteredOrders" 
          stripe 
          border 
          v-loading="orderLoading"
          @row-click="handleOrderRowClick"
          :row-class-name="getOrderRowClassName"
          class="order-table"
          highlight-current-row
        >
          <el-table-column prop="orderNo" label="订单号" width="150" />
          <el-table-column prop="orderType" label="订单类型" width="120">
            <template #default="scope">
              <el-tag :type="getOrderTypeTagType(scope.row.orderType)">
                {{ getOrderTypeText(scope.row.orderType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="customerName" label="客户名称" width="120" />
          <el-table-column prop="amount" label="订单金额" width="120" align="right">
            <template #default="scope">
              ¥{{ scope.row.amount?.toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" width="100">
            <template #default="scope">
              <el-tag :type="getOrderStatusTagType(scope.row.orderStatus)">
                {{ getOrderStatusText(scope.row.orderStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="凭证状态" width="120">
            <template #default="scope">
              <el-tag 
                :type="scope.row.voucherStatus === 'hasVoucher' ? 'danger' : 'success'" 
                size="small"
              >
                {{ getVoucherStatusText(scope.row.voucherStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="voucherNo" label="凭证号" width="150">
            <template #default="scope">
              <span v-if="scope.row.voucherNo" class="voucher-link">
                {{ scope.row.voucherNo }}
              </span>
              <span v-else class="no-voucher">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160" />
          <el-table-column prop="remark" label="备注" min-width="150" />
        </el-table>

        <!-- 订单分页 -->
        <div class="order-pagination">
          <el-pagination
            v-model:current-page="orderPagination.currentPage"
            v-model:page-size="orderPagination.pageSize"
            :page-sizes="[10, 20, 50]"
            :total="orderPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleOrderSizeChange"
            @current-change="handleOrderCurrentChange"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeOrderSelector">取消</el-button>
          <el-button type="primary" @click="confirmOrderSelection" :disabled="!selectedOrderId">
            确认选择
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus, Download, Search, Refresh, View, Edit, Delete, Clock, CircleCheck } from '@element-plus/icons-vue'
import { 
  getAccountingSubjects, 
  getAuxiliarySubjects, 
  generateAccountingEntries,
  validateEntriesBalance,
  getSubjectTypeName,
  getAuxiliaryTypeName
} from '@/services/financeService'

// 文本常量
const texts = {
  title: '财务凭证管理',
  voucherNo: '凭证编号',
  voucherNoPlaceholder: '请输入凭证编号',
  voucherType: '凭证类型',
  purchaseVoucher: '采购凭证',
  salesVoucher: '销售凭证',
  purchase: '采购',
  sales: '销售',
  orderId: '订单号',
  orderIdPlaceholder: '请输入订单号',
  customerName: '客户名称',
  customerNamePlaceholder: '请输入客户名称',
  totalAmount: '总金额',
  totalAmountPlaceholder: '请输入总金额',
  voucherDate: '凭证日期',
  summary: '摘要',
  summaryPlaceholder: '请输入凭证摘要',
  editVoucher: '编辑凭证',
  addVoucher: '新增凭证',
  autoGenerated: '系统自动生成',
  accountingEntries: '会计分录',
  accountingEntriesPreview: '会计分录预览',
  accountingEntriesDescription: '系统将根据订单类型自动生成标准会计分录',
  accountCode: '科目编码',
  accountName: '科目名称',
  debitAmount: '借方金额',
  creditAmount: '贷方金额',
  auxiliary: '辅助核算',
  auxiliaryValue: '辅助核算值',
  balanceCheck: '借贷平衡',
  cashAccount: '库存现金',
  revenueAccount: '主营业务收入',
  inventoryAccount: '库存商品',
  salesIncomeSummary: '收到商品销售收入',
  salesRevenueSummary: '商品销售收入',
  purchaseInventorySummary: '商品采购入库',
  purchasePaymentSummary: '支付采购货款',
  refundSummary: '商品退货退款',
  refundPaymentSummary: '支付退款',
  basicInfo: '基本信息',
  voucherStatus: '凭证状态',
  alreadyHasVoucher: '已有凭证',
  noVoucher: '无凭证',
  statusDraft: '草稿',
  statusApproved: '已审批',
  statusPosted: '已过账',
  statusRejected: '已拒绝',
  approve: '审批',
  post: '过账',
  reject: '拒绝',
  approveConfirm: '确定要审批通过这张凭证吗？',
  postConfirm: '确定要将这张凭证过账吗？过账后将不能再修改。',
  rejectConfirm: '确定要拒绝这张凭证吗？',
  approveSuccess: '凭证审批成功',
  postSuccess: '凭证过账成功',
  rejectSuccess: '凭证拒绝成功',
  autoGenFromOrder: '订单自动生成',
  add: '新增',
  export: '导出',
  pleaseSelect: '请选择',
  dateRange: '日期范围',
  to: '至',
  startDate: '开始日期',
  endDate: '结束日期',
  search: '搜索',
  reset: '重置',
  status: '状态',
  actions: '操作',
  view: '查看',
  edit: '编辑',
  delete: '删除',
  cancel: '取消',
  save: '保存',
  close: '关闭'
}



// 数据相关
const loading = ref(false)
const activeTab = ref('pending') // 当前活跃的tab页

// 模拟更多的凭证数据，包含不同状态
const vouchers = ref([
  {
    id: '1',
    voucherNo: 'V202401001',
    voucherType: 'sales',
    orderId: 'ORD202401001',
    customerName: '田中太郎',
    totalAmount: 15000,
    voucherDate: '2024-01-15',
    status: 'approved',
    summary: '商品销售收入',
    createTime: '2024-01-15 10:30:00',
    isAutoGenerated: true
  },
  {
    id: '2',
    voucherNo: 'V202401002',
    voucherType: 'purchase',
    orderId: 'ORD202401002',
    customerName: '佐藤花子',
    totalAmount: 8500,
    voucherDate: '2024-01-16',
    status: 'pending',
    summary: '商品采购成本',
    createTime: '2024-01-16 14:20:00',
    isAutoGenerated: true
  },
  {
    id: '3',
    voucherNo: 'V202401003',
    voucherType: 'sales',
    orderId: 'ORD202401003',
    customerName: '山田次郎',
    totalAmount: 22000,
    voucherDate: '2024-01-17',
    status: 'pending',
    summary: '电子产品销售',
    createTime: '2024-01-17 09:15:00',
    isAutoGenerated: true
  },
  {
    id: '4',
    voucherNo: 'V202401004',
    voucherType: 'sales',
    orderId: 'ORD202401004',
    customerName: '鈴木美咲',
    totalAmount: 18500,
    voucherDate: '2024-01-18',
    status: 'posted',
    summary: '家电产品销售',
    createTime: '2024-01-18 16:45:00',
    isAutoGenerated: true
  },
  {
    id: '5',
    voucherNo: 'V202401005',
    voucherType: 'purchase',
    orderId: 'ORD202401005',
    customerName: '中村健一',
    totalAmount: 12000,
    voucherDate: '2024-01-19',
    status: 'pending',
    summary: '办公用品采购',
    createTime: '2024-01-19 11:20:00',
    isAutoGenerated: true
  },
  {
    id: '6',
    voucherNo: 'V202401006',
    voucherType: 'sales',
    orderId: 'ORD202401006',
    customerName: '高橋智子',
    totalAmount: 8800,
    voucherDate: '2024-01-20',
    status: 'approved',
    summary: '书籍销售',
    createTime: '2024-01-20 13:10:00',
    isAutoGenerated: true
  }
])

// 已移除状态计数功能

// 根据当前tab过滤凭证
const filteredVouchersByTab = computed(() => {
  let filtered = vouchers.value
  
  // 先按tab状态过滤
  if (activeTab.value === 'pending') {
    filtered = filtered.filter(v => v.status === 'pending')
  } else if (activeTab.value === 'approved') {
    filtered = filtered.filter(v => v.status === 'approved')
  }
  
  // 再应用搜索条件
  if (searchForm.voucherNo) {
    filtered = filtered.filter(v => 
      v.voucherNo.toLowerCase().includes(searchForm.voucherNo.toLowerCase())
    )
  }
  
  if (searchForm.voucherType) {
    filtered = filtered.filter(v => v.voucherType === searchForm.voucherType)
  }
  
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.dateRange as [string, string]
    filtered = filtered.filter(v => 
      v.voucherDate >= startDate && v.voucherDate <= endDate
    )
  }
  
  return filtered
})

// 凭证详情弹窗
const voucherDetailDialog = reactive({
  visible: false,
  data: null as any
})

// 订单选择器相关
const showOrderSelector = ref(false)
const selectedOrderId = ref('')
const orderLoading = ref(false)

// 订单搜索表单
const orderSearchForm = reactive({
  orderNo: '',
  orderType: '',
  orderStatus: ''
})

// 订单分页
const orderPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 模拟订单数据
const orders = ref([
  {
    id: 'ORD202401001',
    orderNo: 'ORD202401001',
    orderType: 'sales',
    customerName: '田中太郎',
    amount: 15000,
    orderStatus: 'completed',
    createTime: '2024-01-15 10:30:00',
    remark: '商品销售收入',
    voucherStatus: 'hasVoucher', // 已有凭证
    voucherNo: 'V202401001' // 对应的凭证号
  },
  {
    id: 'ORD202401002',
    orderNo: 'ORD202401002',
    orderType: 'purchase',
    customerName: '佐藤花子',
    amount: 8500,
    orderStatus: 'completed',
    createTime: '2024-01-16 14:20:00',
    remark: '商品采购成本',
    voucherStatus: 'noVoucher', // 无凭证
    voucherNo: null
  },
  {
    id: 'ORD202401003',
    orderNo: 'ORD202401003',
    orderType: 'sales',
    customerName: '山田次郎',
    amount: 22000,
    orderStatus: 'completed',
    createTime: '2024-01-17 09:15:00',
    remark: '电子产品销售',
    voucherStatus: 'noVoucher', // 无凭证
    voucherNo: null
  },
  {
    id: 'ORD202401004',
    orderNo: 'ORD202401004',
    orderType: 'refund',
    customerName: '鈴木美咲',
    amount: -5000,
    orderStatus: 'completed',
    createTime: '2024-01-18 16:45:00',
    remark: '商品退货退款',
    voucherStatus: 'hasVoucher', // 已有凭证
    voucherNo: 'V202401004' // 对应的凭证号
  }
])

// 过滤后的订单列表
const filteredOrders = computed(() => {
  let filtered = orders.value
  
  if (orderSearchForm.orderNo) {
    filtered = filtered.filter(order => 
      order.orderNo.toLowerCase().includes(orderSearchForm.orderNo.toLowerCase())
    )
  }
  
  if (orderSearchForm.orderType) {
    filtered = filtered.filter(order => order.orderType === orderSearchForm.orderType)
  }
  
  if (orderSearchForm.orderStatus) {
    filtered = filtered.filter(order => order.orderStatus === orderSearchForm.orderStatus)
  }
  
  return filtered
})

// 预览会计分录
const previewEntries = computed(() => {
  if (!voucherDialog.form.orderId || !voucherDialog.form.totalAmount) {
    return []
  }
  
  const order = orders.value.find(o => o.id === voucherDialog.form.orderId)
  if (!order) return []
  
  return generatePreviewEntries(order, voucherDialog.form.totalAmount)
})

// 搜索表单
const searchForm = reactive({
  voucherNo: '',
  voucherType: '',
  dateRange: [] as string[]
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 凭证弹窗
const voucherDialog = reactive({
  visible: false,
  isEdit: false,
  form: {
    id: '',
    voucherNo: '',
    voucherType: '',
    orderId: '',
    customerName: '',
    totalAmount: 0,
    voucherDate: '',
    status: 'pending',
    summary: ''
  }
})

const voucherFormRef = ref<FormInstance>()

// 表单验证规则
const voucherRules = {
  voucherType: [{ required: true, message: '请选择凭证类型', trigger: 'change' }],
  orderId: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '请输入总金额', trigger: 'blur' }],
  voucherDate: [{ required: true, message: '请选择凭证日期', trigger: 'change' }]
}

// 方法

// Tab切换处理
function handleTabChange(tabName: string) {
  activeTab.value = tabName
  // 重置分页到第一页
  pagination.currentPage = 1
  // 更新分页总数
  pagination.total = filteredVouchersByTab.value.length
}

// 审批凭证
function approveVoucher(voucher: any) {
  ElMessageBox.confirm(
    texts.approveConfirm,
    '确认审批',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 更新凭证状态
    const index = vouchers.value.findIndex(v => v.id === voucher.id)
    if (index > -1) {
      vouchers.value[index].status = 'approved'
      ElMessage.success(texts.approveSuccess)
    }
  }).catch(() => {
    ElMessage.info('已取消审批')
  })
}



function searchVouchers() {
  loading.value = true
  // 模拟搜索API调用
  setTimeout(() => {
    loading.value = false
    ElMessage.success('搜索完成')
  }, 1000)
}

function resetSearch() {
  searchForm.voucherNo = ''
  searchForm.voucherType = ''
  searchForm.dateRange = []
  searchVouchers()
}

function openVoucherDialog(voucher?: any) {
  if (voucher) {
    voucherDialog.isEdit = true
    Object.assign(voucherDialog.form, voucher)
  } else {
    voucherDialog.isEdit = false
    Object.assign(voucherDialog.form, {
      id: '',
      voucherNo: `V${new Date().getFullYear()}${String(Date.now()).slice(-5)}`,
      voucherType: '',
      orderId: '',
      customerName: '',
      totalAmount: 0,
      voucherDate: new Date().toISOString().split('T')[0],
      summary: ''
    })
  }
  voucherDialog.visible = true
}

function closeVoucherDialog() {
  voucherDialog.visible = false
  voucherFormRef.value?.resetFields()
}

function saveVoucher() {
  voucherFormRef.value?.validate((valid) => {
    if (valid) {
      if (voucherDialog.isEdit) {
        // 编辑凭证
        const index = vouchers.value.findIndex(v => v.id === voucherDialog.form.id)
        if (index > -1) {
          Object.assign(vouchers.value[index], voucherDialog.form)
          ElMessage.success('凭证更新成功')
        }
      } else {
        // 新增凭证
        const newVoucher = {
          ...voucherDialog.form,
          id: Date.now().toString(),
          status: 'pending',
          createTime: new Date().toLocaleString(),
          isAutoGenerated: false
        }
        vouchers.value.unshift(newVoucher)
        ElMessage.success('凭证创建成功')
      }
      
      // 更新分页总数
      pagination.total = vouchers.value.length
      closeVoucherDialog()
    }
  })
}

function viewVoucher(voucher: any) {
  // 获取完整的凭证数据（包括会计分录）
  const fullVoucher = {
    ...voucher,
    entries: generateMockEntries(voucher)
  }
  voucherDetailDialog.data = fullVoucher
  voucherDetailDialog.visible = true
}

function closeVoucherDetailDialog() {
  voucherDetailDialog.visible = false
  voucherDetailDialog.data = null
}

function editVoucherFromDetail() {
  if (voucherDetailDialog.data) {
    openVoucherDialog(voucherDetailDialog.data)
    closeVoucherDetailDialog()
  }
}

// 生成预览会计分录
function generatePreviewEntries(order: any, amount: number) {
  // 获取辅助核算项
  const auxiliarySubjects = getAuxiliarySubjects('1002') // 银行存款的辅助核算项
  
  // 使用新的会计科目服务生成会计分录
  const entries = generateAccountingEntries(order.orderType, amount, order.customerName, auxiliarySubjects)
  
  // 验证借贷平衡
  if (!validateEntriesBalance(entries)) {
    ElMessage.warning('会计分录借贷不平衡，请检查')
  }
  
  return entries
}

// 生成模拟的会计分录数据
function generateMockEntries(voucher: any) {
  if (voucher.voucherType === 'sales') {
    return [
      {
        id: '1',
        accountCode: '1001',
        accountName: texts.cashAccount,
        debitAmount: 0,
        creditAmount: voucher.totalAmount,
        summary: texts.salesIncomeSummary,
        auxiliary: 'customer',
        auxiliaryValue: voucher.customerName
      },
      {
        id: '2',
        accountCode: '6001',
        accountName: texts.revenueAccount,
        debitAmount: 0,
        creditAmount: voucher.totalAmount,
        summary: texts.salesRevenueSummary,
        auxiliary: 'customer',
        auxiliaryValue: voucher.customerName
      }
    ]
  } else if (voucher.voucherType === 'purchase') {
    return [
      {
        id: '3',
        accountCode: '1405',
        accountName: '库存商品',
        debitAmount: voucher.totalAmount,
        creditAmount: 0,
        summary: '商品采购入库',
        auxiliary: 'supplier',
        auxiliaryValue: voucher.customerName
      },
      {
        id: '4',
        accountCode: '1001',
        accountName: '库存现金',
        debitAmount: 0,
        creditAmount: voucher.totalAmount,
        summary: '支付采购货款',
        auxiliary: 'supplier',
        auxiliaryValue: voucher.customerName
      }
    ]
  } else if (voucher.voucherType === 'refund') {
    return [
      {
        id: '5',
        accountCode: '6001',
        accountName: '主营业务收入',
        debitAmount: Math.abs(voucher.totalAmount),
        creditAmount: 0,
        summary: '商品退货退款',
        auxiliary: 'customer',
        auxiliaryValue: voucher.customerName
      },
      {
        id: '6',
        accountCode: '1001',
        accountName: '库存现金',
        debitAmount: 0,
        creditAmount: Math.abs(voucher.totalAmount),
        summary: '支付退款',
        auxiliary: 'customer',
        auxiliaryValue: voucher.customerName
      }
    ]
  }
  return []
}

function editVoucher(voucher: any) {
  openVoucherDialog(voucher)
}

function deleteVoucher(voucher: any) {
  ElMessageBox.confirm(
    `确定要删除凭证 ${voucher.voucherNo} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 从列表中删除凭证
    const index = vouchers.value.findIndex(v => v.id === voucher.id)
    if (index > -1) {
      vouchers.value.splice(index, 1)
      // 更新分页总数
      pagination.total = vouchers.value.length
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

function exportVouchers() {
  ElMessage.success('导出功能开发中...')
}

function handleSizeChange(val: number) {
  pagination.pageSize = val
  searchVouchers()
}

function handleCurrentChange(val: number) {
  pagination.currentPage = val
  searchVouchers()
}

// 页面加载
onMounted(() => {
  // 初始化分页总数
  pagination.total = filteredVouchersByTab.value.length
  searchVouchers()
  // 初始化订单分页总数
  orderPagination.total = orders.value.length
})

// 订单选择器相关方法
function getOrderInfo(orderId: string) {
  return orders.value.find(order => order.id === orderId)
}

function closeOrderSelector() {
  showOrderSelector.value = false
  selectedOrderId.value = ''
}

function searchOrders() {
  orderLoading.value = true
  // 模拟搜索API调用
  setTimeout(() => {
    orderLoading.value = false
    ElMessage.success('订单搜索完成')
  }, 500)
}

function resetOrderSearch() {
  orderSearchForm.orderNo = ''
  orderSearchForm.orderType = ''
  orderSearchForm.orderStatus = ''
  searchOrders()
}

function selectOrder(row: any) {
  selectedOrderId.value = row.id
  // 高亮显示选中的行
  ElMessage.info(`已选择订单：${row.orderNo}`)
}

// 处理订单行点击
function handleOrderRowClick(row: any) {
  // 如果订单已有凭证，则不允许选择
  if (row.voucherStatus === 'hasVoucher') {
    ElMessage.warning(`订单 ${row.orderNo} 已有凭证 ${row.voucherNo}，不能重复录入`)
    return
  }
  
  // 选择订单
  selectOrder(row)
}

// 获取订单行的CSS类名
function getOrderRowClassName({ row }: { row: any }) {
  // 如果订单已有凭证，添加特殊样式
  if (row.voucherStatus === 'hasVoucher') {
    return 'order-row-has-voucher'
  }
  
  // 如果是选中的订单，添加选中样式
  if (row.id === selectedOrderId.value) {
    return 'selected-order-row'
  }
  
  return ''
}

function confirmOrderSelection() {
  if (selectedOrderId.value) {
    const selectedOrder = orders.value.find(order => order.id === selectedOrderId.value)
    if (selectedOrder) {
      voucherDialog.form.orderId = selectedOrder.id
      voucherDialog.form.customerName = selectedOrder.customerName
      voucherDialog.form.totalAmount = Math.abs(selectedOrder.amount)
      
      // 根据订单类型自动设置凭证类型
      if (selectedOrder.orderType === 'sales') {
        voucherDialog.form.voucherType = 'sales'
      } else if (selectedOrder.orderType === 'purchase') {
        voucherDialog.form.voucherType = 'purchase'
      }
      
      closeOrderSelector()
      ElMessage.success('订单关联成功')
    }
  }
}

function getOrderTypeTagType(orderType: string) {
  const types: Record<string, string> = {
    sales: 'success',
    purchase: 'warning',
    refund: 'danger'
  }
  return types[orderType] || 'info'
}

function getOrderTypeText(orderType: string) {
  const texts: Record<string, string> = {
    sales: '销售订单',
    purchase: '采购订单',
    refund: '退款订单'
  }
  return texts[orderType] || '未知类型'
}

function getOrderStatusTagType(orderStatus: string) {
  const types: Record<string, string> = {
    completed: 'success',
    processing: 'warning',
    cancelled: 'danger'
  }
  return types[orderStatus] || 'info'
}

function getOrderStatusText(orderStatus: string) {
  const texts: Record<string, string> = {
    completed: '已完成',
    processing: '处理中',
    cancelled: '已取消'
  }
  return texts[orderStatus] || '未知状态'
}

// 获取凭证状态文本
function getVoucherStatusText(voucherStatus: string) {
  const texts: Record<string, string> = {
    hasVoucher: '已有凭证',
    noVoucher: '无凭证'
  }
  return texts[voucherStatus] || voucherStatus
}

function handleOrderSizeChange(val: number) {
  orderPagination.pageSize = val
  searchOrders()
}

function handleOrderCurrentChange(val: number) {
  orderPagination.currentPage = val
  searchOrders()
}

// 获取状态标签类型
function getStatusType(status: string) {
  const types: Record<string, string> = {
    pending: 'warning',
    approved: 'success'
  }
  return types[status] || 'info'
}

// 获取状态文本
function getStatusText(status: string) {
  const texts: Record<string, string> = {
    pending: '待审批',
    approved: '已审批'
  }
  return texts[status] || status
}
</script>

<style scoped>
.voucher-manage {
  padding: 20px;
}



.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-card .el-card__body {
  padding: 10px 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 订单选择器样式 */
.order-selector {
  position: relative;
}

/* 已有凭证的订单行样式 */
.order-row-has-voucher {
  background-color: #fef0f0 !important;
  color: #f56c6c;
  cursor: not-allowed;
}

.order-row-has-voucher:hover {
  background-color: #fef0f0 !important;
}

/* 凭证链接样式 */
.voucher-link {
  color: #409eff;
  text-decoration: underline;
  cursor: pointer;
}

.voucher-link:hover {
  color: #337ecc;
}

.no-voucher {
  color: #909399;
  font-style: italic;
}

.order-info {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-amount {
  color: #67c23a;
  font-weight: 500;
}

.order-selector-content {
  max-height: 600px;
  overflow-y: auto;
}

.order-search-form {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.order-table {
  margin-bottom: 20px;
}

.order-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 表格行点击效果 */
.order-table .el-table__row {
  cursor: pointer;
  transition: background-color 0.2s;
}

.order-table .el-table__row:hover {
  background-color: #f0f9ff !important;
}

.order-table .el-table__row.selected {
  background-color: #e6f7ff !important;
}

/* 凭证详情样式 */
.voucher-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.detail-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.detail-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 100px;
  margin-right: 12px;
}

.detail-item .value {
  color: #303133;
  flex: 1;
}

.detail-item .value.amount {
  color: #67c23a;
  font-weight: 600;
}

.debit-amount {
  color: #e6a23c;
  font-weight: 500;
}

.credit-amount {
  color: #67c23a;
  font-weight: 500;
}

/* 订单选择器样式优化 */
.selected-order-row {
  background-color: #e6f7ff !important;
  border-left: 4px solid #409eff !important;
}

.selected-order-row:hover {
  background-color: #e6f7ff !important;
}

/* 会计分录预览样式 */
.accounting-entries-preview {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  background: #fafafa;
}

.preview-header {
  margin-bottom: 16px;
}

.preview-footer {
  margin-top: 16px;
  text-align: center;
}

/* 订单信息显示优化 */
.order-info {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  background: #f0f9ff;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.order-amount {
  color: #67c23a;
  font-weight: 600;
  font-size: 14px;
}

/* 凭证表单页面样式 */
.voucher-form-page {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f5f5f5;
  z-index: 1000;
  overflow-y: auto;
}

.page-header {
  background: white;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.form-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.action-buttons {
  text-align: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-buttons .el-button {
  margin: 0 10px;
  min-width: 100px;
}

/* Tab页样式 */
.voucher-tabs {
  margin-bottom: 20px;
}

.voucher-tabs .el-tabs__header {
  margin-bottom: 10px;
}

.voucher-tabs .el-tabs__content {
  overflow: visible;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 6px;
}



/* Tab页内容区样式 */
.el-tab-pane {
  min-height: 60px;
  padding-top: 10px;
}

/* 状态标签样式优化 */
.el-tag {
  border-radius: 12px;
  font-size: 12px;
  padding: 0 8px;
}

/* 操作按钮样式优化 */
.el-table .el-button {
  margin: 2px;
  border-radius: 4px;
}

.el-table .el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.el-table .el-button--warning {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

.el-table .el-button--info {
  background-color: #909399;
  border-color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 10px;
  }
  
  .form-section {
    margin-bottom: 20px;
  }
  
  .action-buttons .el-button {
    margin: 5px;
    min-width: 80px;
  }
  
  .tab-label {
    font-size: 12px;
  }
  
  .tab-label .el-icon {
    display: none;
  }
  
  .el-table .el-button {
    padding: 4px 8px;
    font-size: 12px;
  }
  
  .el-table .el-button .el-icon {
    margin-right: 2px;
  }
}
</style>

